﻿using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using DonetSpider;
using DonetSpider.config;
using DonetSpider.Db;
using DonetSpider.http;
using DonetSpider.Log;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DonetSpider
{
    /// <summary>
    /// www.kanjuji.com 网站爬取类
    /// </summary>
    public class Kanjuji : MovieSpiderBase
    {

        public Kanjuji(string url, string name, IMovieDb Writer, IHttpHelper http) : base(url, name, Writer, http)
        {
        }

        public override string Host => "https://www.kanjuji.com/";
        public static string SearchUrl => "https://www.kanjuji.com/index.php/vod/search.html?wd={0}&submit=";

        protected override void _down(string myPath, string myMurl, Items i)
        {
            base.down(myPath, myMurl, i);
        }

        protected override void _run()
        {
            var item = this.Play(Url);
            Html = _Http.GetHTMLByURLAsync(Url).GetAwaiter().GetResult();
            if (item != null && LastItem?.Name != item.Name) WriteItems(new List<Items> { item });
        }

        public override SearchResult Seach(string key,int n)
        {
            var res = new SearchResult();
            var url = n == 1 ? GetUrl(key) : string.Format(SearchUrl, key);
            var html = _Http.GetHTMLByURLAsync(url).GetAwaiter().GetResult();
            using (IHtmlDocument dom = new HtmlParser().Parse(html))
            {
                var a = dom.QuerySelectorAll("a"); // 全部a 标签
                var items = a.Where(m => (!string.IsNullOrEmpty(m.ClassName)) && m.ClassName.Contains("stui-vodlist__thumb lazyload")).Select(m => (IHtmlAnchorElement)m).ToList();

                Console.WriteLine($"查询结果{items?.Count ?? 0} 条符合条件");
                res.Items = items?.Select(m => new SearchResultItems
                {
                    Title = m.Title + "_" + m.TextContent,
                    ImgUrl = m.Attributes[3].Value,
                    LinkUrl = m.PathName
                }).ToList() ?? new List<SearchResultItems>();

                res.Links = dom.QuerySelectorAll(".stui-page a")?.Select(m => new SearchResultItems
                {
                    Title = m.TextContent,
                    LinkUrl = m.Attributes[0].Value
                }).ToList() ?? new List<SearchResultItems>();


            }

            return res;
        }


        public override MovieInfo To(MovieInfoReques info)
        {
            var res = new MovieInfo();

            if (info.Id > 0) {
                var exit = sqliteWriter.SelectTitleById(info.Id+"")?.FirstOrDefault();
                if (exit != null) {
                    info.StartUrl = exit.StartUrl;
                    res.Id = exit.Id;
                }
            }

            var url = GetUrl(info.StartUrl);
            var html = _Http.GetHTMLByURLAsync(url).GetAwaiter().GetResult();
            using (IHtmlDocument dom = new HtmlParser().Parse(html))
            {
                res.ImageUrl = dom.QuerySelector(".stui-content__thumb img")?.Attributes.FirstOrDefault(m => m.Name == "data-original")?.Value;
                res.Name = dom.QuerySelector(".stui-content__detail .title")?.TextContent;
                res.Des = dom.QuerySelector(".stui-content__desc")?.TextContent;
                dom.QuerySelectorAll(".stui-pannel")
                    ?.ToList()
                    .ForEach(m =>
                    {
                        var key = m.QuerySelector("h3")?.TextContent + "";
                        if (!string.IsNullOrEmpty(key)) { 
                            var list = m.QuerySelectorAll("li a")?.ToList().Select(m => new MovieSourse
                            {
                                SourseUrl = m.Attributes[0].Value,
                                Title = m.TextContent
                            }).ToList() ?? new List<MovieSourse>();
                            if (list.Any()) {
                                res.Sourse[key] = list;
                            }
                        }
                        
                    });


            }
            return res;
        }

        public override Items Play(string url)
        {
            
            Url = GetUrl(url);
            Html = _Http.GetHTMLByURLAsync(Url).GetAwaiter().GetResult();
            using (IHtmlDocument dom = new HtmlParser().Parse(Html))
            {
                var data = dom.Scripts.Where(m => m.InnerHtml.Contains(".m3u8")).ToList();
                Console.WriteLine($"查询结果{data?.Count ?? 0} 条符合条件");
                if (data != null && data.Count > 0)
                {
                    var player_aaaa = data[0].InnerHtml.Replace("var player_aaaa=", "");
                    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(player_aaaa);
                    NextUrl = obj.ContainsKey("link_next") && !string.IsNullOrEmpty(obj["link_next"] + "") ? $"{Host}{obj["link_next"]}" : null;
                    url = obj.ContainsKey("url") && !string.IsNullOrEmpty(obj["url"] + "") ? $"{obj["url"]}" : null;
                    var name = Url.Split("/").Last().Split(".").First();
                    return new Items { PId = PId, Name = name, DataMsg = player_aaaa, Url = Url, MUrl = url };
                }
            }
            return null;
        }
    }
}
